package com.health.mapp.service;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.ImMsgNotice;
import com.health.db.model.ImMsgNoticeExample;
import com.health.db.model.UserLIST;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetStuffOpenIdResp;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IService;
import com.wxtools.bean.result.WxError;
import com.wxtools.bean.result.WxOAuth2AccessTokenResult;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by yangyayun on 2018/1/16.
 */
public class StuffBind extends HttpServlet{

    private IService mpService;
    private IUserLISTService userLISTService;
    private IStuffListService stuffListService;
    private ImMsgNoticeService imMsgNoticeService  ;


    public void init(ServletConfig config) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext servletContext = request.getSession().getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        mpService = (IService) applicationContext.getBean("mpService");
        stuffListService = (IStuffListService) applicationContext.getBean("stuffListService");
        userLISTService= (IUserLISTService) applicationContext.getBean("userLISTService");
        imMsgNoticeService= (ImMsgNoticeService) applicationContext.getBean("imMsgNoticeService");

        GetStuffOpenIdResp _resp = new GetStuffOpenIdResp();

        String userPhone=request.getParameter("phone");
        String smsCode=request.getParameter("code");
        String accessToken=request.getParameter("accessToken");
        String refreshToken=request.getParameter("refreshToken");
        String openId=request.getParameter("openId");


        if (StringUtils.isBlank(userPhone)||
                StringUtils.isBlank(smsCode) ||
                StringUtils.isEmpty(accessToken)||
                StringUtils.isEmpty(refreshToken)||
                StringUtils.isEmpty(openId)) {

            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
        }

        UserLIST user = null;
        StuffDetailDto stuffDetail = stuffListService.selectByStuffNo(userPhone);
        if (null!=stuffDetail)
        {
            user = userLISTService.selectByUserId(stuffDetail.getStuffid());
        }

        if (null != user) {

            //检验是否意见绑定了其他手机号
            List<UserLIST> userLISTS = userLISTService.selectByWXOpenid(openId);
            if (null != userLISTS && userLISTS.size() > 0 && !userLISTS.get(0).getUserNo().equals(userPhone)) {
                _resp.setErrorCode(-1);
                _resp.setErrorMsg("该微信账户已绑定其他账号");
            }

            //校验短信验证码
            ImMsgNoticeExample notice = new ImMsgNoticeExample();
            notice.setRandom(smsCode);
            notice.setNoticeReceiveAddress(userPhone);
            notice.setIsUsedFlag((short) 1);
            notice.setModetypeid(9);
            List<ImMsgNotice> list=imMsgNoticeService.selectByExample(notice);

            if (list.size()!=1) {
                _resp.setErrorCode(ResultCode.SMS_ERROR);
                _resp.setErrorMsg(ResultCode.SMS_ERROR_NOTE);
            }

            //校验是否openid正确
            try {

                WxError wxError=mpService.oauth2CheckAccessToken(accessToken,openId);
                if (wxError.getErrcode()==0)
                {
                    user.setWxopenid(openId);
                    int result=userLISTService.updateByPrimaryKey(user);
                    if (result<0)
                    {
                        //绑定成功
                        _resp.setErrorCode(-1);
                        _resp.setErrorMsg("绑定失败");
                    }

                }else
                {
                    try {
                        //强制刷新
                        WxOAuth2AccessTokenResult tokenResult= mpService.oauth2ToGetRefreshAccessToken(refreshToken);
                        user.setWxopenid(tokenResult.getOpenid());
                        int result=userLISTService.updateByPrimaryKey(user);
                        if (result<0)
                        {
                            _resp.setErrorCode(-1);
                            _resp.setErrorMsg("绑定失败");
                        }

                    }catch (Exception e)
                    {
                        _resp.setErrorCode(-100);
                        _resp.setErrorMsg("绑定超时");
                    }

                }

            }catch (Exception e)
            {
                _resp.setErrorCode(-2);
                _resp.setErrorMsg("绑定失败");
            }




        }else
        {
            _resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
            _resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
        }

        String callbackName = request.getParameter("jsonpCallback");// 客户端请求参数
        String jsonStr = JSONObject.fromObject(_resp).toString();
        String renderStr = callbackName+"("+jsonStr+")";
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "cache-control,content-type,hash-referer,x-requested-with");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(renderStr);
        out.println("\r\n");
        out.flush();
        out.close();

    }
}
